package com.sdry.web.controller.llm;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.sdry.model.barCodeOperation.BarCodeOperation;
import com.sdry.model.jyy.Receive;
import com.sdry.model.jyy.ReceiveDetail;
import com.sdry.model.jyy.ReceiveDetailQuality;
import com.sdry.model.llm.BarCode;
import com.sdry.model.llm.LlmCancellingStocks;
import com.sdry.model.llm.LlmCancellingStocksDetail;
import com.sdry.model.llm.LlmCodemarkReturn;
import com.sdry.model.lz.CodeMark;
import com.sdry.model.lz.Materiel;
import com.sdry.model.zc.ZcInventoryInfoEntity;
import com.sdry.model.zc.ZcMaterielAndTrayEntity;
import com.sdry.model.zc.ZcMaterielInfoEntity;
import com.sdry.service.barCodeOperation.BarCodeOperationService;
import com.sdry.service.jyy.ReceiveDetailService;
import com.sdry.service.jyy.ReceiveService;
import com.sdry.service.llm.CancellingStockDetailService;
import com.sdry.service.llm.CancellingStockService;
import com.sdry.service.lz.InventoryService;
import com.sdry.service.lz.MaterielService;
import com.sdry.service.lz.StockOutOrderService;
import com.sdry.service.zc.ZcBindAndUnbindService;
import com.sdry.utils.ResponseUtil;

import net.sf.json.JSONObject;

/**
 * App接口
 * @Title:AppInterfaces
 * @Package com.sdry.web.controller.llm
 * @author llm
 * @date 2019年5月17日
 * @version 1.0
 */
@Controller
@RequestMapping("/appInterfaces")
public class AppInterfaces {

	@Resource
	private CancellingStockService cancellingStockService;
	@Resource
	private CancellingStockDetailService cancellingStockDetailService;
	@Resource
	private StockOutOrderService stockOutService;
	@Resource
	private InventoryService inventoryService;
	@Resource
	private ReceiveDetailService receiveDetailService;
	@Resource
	private ReceiveService receiveService;
	@Resource
	private BarCodeOperationService barCodeOperationService;
	@Resource
	private MaterielService materielService;
	@Resource
	private ZcBindAndUnbindService zcBindAndUnbindService;
	/**
	 * 查询所有退库单
	 * @Title:appGetCancellingStock  
	 * @param response
	 */
	@RequestMapping("/appGetCancellingStock")
	public void appGetCancellingStock(HttpServletResponse response){
		List<LlmCancellingStocks> list = cancellingStockService.getAllCancellingStock();
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("status", "1");
		jsonObject.put("data", list);
		try {
			ResponseUtil.write(response, jsonObject);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 根据退库单号查询详情
	 * @Title:appGetCancellingStockDetailByNumber  
	 * @param cancellingNumber 退库单号
	 * @param response
	 */
	@RequestMapping("/appGetCancellingStockDetailByNumber")
	public void appGetCancellingStockDetailByNumber(String cancellingNumber, HttpServletResponse response){
		List<LlmCancellingStocksDetail> list = cancellingStockDetailService.getCancellingStockDetailByNumber(cancellingNumber);
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("status", "1");
		jsonObject.put("data", list);
		try {
			ResponseUtil.write(response, jsonObject);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * app提交退库单的详细修改实际数量和出库状态
	 * @param json app提交的出库单详细实体
	 */
	@RequestMapping("/appSubmitCancellingStockDetail")
	public void appSubmitOutStockOrderDetail(HttpServletResponse response, String person, String json){
		String addStr = "";
		//json转list集合
		JSONObject jsonObject = new JSONObject();
		Gson gson = new Gson();
		List<LlmCancellingStocksDetail> cancellingStocksDetailPDAEntityList = gson.fromJson(json, new TypeToken<List<LlmCancellingStocksDetail>>() {}.getType());
		LlmCodemarkReturn codemark = new LlmCodemarkReturn();
		if(cancellingStocksDetailPDAEntityList.size() > 0) {
			//--------------给历史记录表插入数据--------------
			SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			String time = format.format(new Date());
			BarCodeOperation bar = new BarCodeOperation();
			for(LlmCancellingStocksDetail detail : cancellingStocksDetailPDAEntityList){
				bar.setOperator(Long.parseLong(person));
				bar.setMaterielId(detail.getMaterialId());
				bar.setOperatingTime(time);
				bar.setType("退库");
				bar.setResult("成功");
				for(CodeMark cm : detail.getReceiveCode()){
					ReceiveDetailQuality byCode = inventoryService.queryReceiveByCode(cm.getCode());
					bar.setBatch(byCode.getPici());
					bar.setBarCode(cm.getCode());
					barCodeOperationService.insert(bar);
				}
			}
			//--------------end--------------
			for (LlmCancellingStocksDetail cancellingStocksDetail : cancellingStocksDetailPDAEntityList) {
				if ("".equals(cancellingStocksDetail.getActualQuantity())) {
					cancellingStocksDetail.setActualQuantity(0);
				}
				//1.根据APP传递过来的数据修改数量
				cancellingStockDetailService.updateCancellingStockDetailActNum(cancellingStocksDetail.getId() + "",
						cancellingStocksDetail.getActualQuantity() + "", cancellingStocksDetail.getSingle_num() + "",
						cancellingStocksDetail.getBig_num() + "", cancellingStocksDetail.getSmall_num() + "");
				//2.减库存数量(遍历cancellingStocksDetailPDAEntityList)
				codemark.setCancelling_stock_detail_id(cancellingStocksDetail.getId());
				for (int j = 0; j < cancellingStocksDetail.getReceiveCode().size(); j++) {
					addStr += cancellingStocksDetail.getReceiveCode().get(j).getCode() + ",";
					//根据收货单详情id查询相应的物料
					//Materiel materiel = stockOutService.queryMaterielByReceiveDetailId(outStockOrderDetailPDAEntityList.get(i).getReceiveCode().get(j).getReceive_detail_id());
					//=============1.根据质检单详情id查询质检单=============
					ReceiveDetailQuality receiveDetailQuality = stockOutService.queryReceiveDetailQualityById(cancellingStocksDetail.getReceiveCode().get(j).getReceive_detail_id());
					//=============2.根据质检单中的物料id和批次减库存=============
					String code = cancellingStocksDetail.getReceiveCode().get(j).getCode();
					CodeMark cm = cancellingStockDetailService.queryCodeByCode(code);
					if(cm != null){
						if(cm.getIs_ng() == 0){
							stockOutService.reductionInventory(cancellingStocksDetail.getMateriel().getId() + "",
									receiveDetailQuality.getPici(), cancellingStocksDetail.getReceiveCode().get(j).getNum() + "");
						}else{
							cancellingStockDetailService.reductionInventory(cancellingStocksDetail.getMateriel().getId() + "",
									receiveDetailQuality.getPici(), cancellingStocksDetail.getReceiveCode().get(j).getNum() + "");
						}
						/*stockOutService.reductionInventoryCache(cancellingStocksDetail.getMateriel().getId() + "",
								receiveDetailQuality.getPici(), cancellingStocksDetail.getReceiveCode().get(j).getNum() + "");*/
					}
					//根据质检单中的物料id和批次减缓存库存
					Date date = new Date();
					SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
					ZcMaterielAndTrayEntity zcMaterielAndTrayEntity = new ZcMaterielAndTrayEntity();
					//String tray_code = System.currentTimeMillis()+"";
					//zcMaterielAndTrayEntity.setTray_code(tray_code);
					zcMaterielAndTrayEntity.setMateriel_code(addStr);
					zcMaterielAndTrayEntity.setBinding_person(Long.parseLong(person));
					zcMaterielAndTrayEntity.setBinding_date(sdf.format(date));
					zcMaterielAndTrayEntity.setTargetRegion("");
					//zcMaterielAndTrayEntity.setLocation_code(location_code);
					int affact2 = zcBindAndUnbindService.bindAndUp2SpecialArea(zcMaterielAndTrayEntity);
					//=============3.删除Codemark表的数据=============
					stockOutService.deleteCodemarkOutByCode(cancellingStocksDetail.getReceiveCode().get(j).getCode());
					//=============4.给CodeMark表添加数据=============
					codemark.setCode(cancellingStocksDetail.getReceiveCode().get(j).getCode());
					codemark.setNum(cancellingStocksDetail.getReceiveCode().get(j).getNum());
					cancellingStockDetailService.insert(codemark);
				}
				
				//5.修改退库单状态
				Map<String, Object> map = new HashMap<>();
				map.put("cancellingNumber", cancellingStocksDetail.getCancellingNumber());
				map.put("fieldName", "status");
				map.put("fieldValue", "1");
				cancellingStockService.updateConcellingStock2(map);
			}
			jsonObject.put("status", "1");
			jsonObject.put("data", "退库成功");
		} else {
			jsonObject.put("status", "0");
			jsonObject.put("message", "提交数据为空");
		}
		try {
			ResponseUtil.write(response, jsonObject);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	/**
	 * app提交的退库单详情
	 * @Title:appSubmitCancellingStockDetail   
	 * @param json
	 * @param response
	 */
	/*@RequestMapping("/appSubmitCancellingStockDetail")
	public void appSubmitCancellingStockDetail(String json, HttpServletResponse response){
		//json转list集合
		List<LlmCancellingStocksDetail> list = new ArrayList<>();
		Gson gson = new Gson();
		list = gson.fromJson(json, new TypeToken<List<LlmCancellingStocksDetail>>() {}.getType());
		String status = "0";
		String data = "未退库";
		if(list.size() > 0){
			Map<String, Object> map = new HashMap<>();
			LlmCancellingStocks cancellingStock = cancellingStockService.getCancellingStockByNumber(list.get(0).getCancellingNumber());
			Integer source = cancellingStock.getSource();
			Long warehouseId = cancellingStock.getWarehouseId();
			Long customerId = cancellingStock.getClientId();
			for(LlmCancellingStocksDetail detail : list){
				if(detail.getActualQuantity() >= 0 && detail.getId() != null && !"".equals(detail.getId()) && detail.getMaterialId() != null && !"".equals(detail.getMaterialId())){
					if ("".equals(detail.getActualQuantity())) {
						detail.setActualQuantity(0);
					}
					//修改退库单详情的实际退库数量
					________________________________修改前start___________________________________
					map.put("id", detail.getId());
					map.put("fieldName", "actualQuantity");
					map.put("fieldValue", detail.getActualQuantity());

					int affectRow = cancellingStockDetailService.updateCancellingStockDetail2(detail.getId() + "",
							detail.getActualQuantity() + "", detail.getSingle_num() + "", detail.getBig_num() + "", detail.getSmall_num() + "");
					//int affectRow = cancellingStockDetailService.updateCancellingStockDetail2(map);
					___________________________________end_______________________________________
					if(affectRow > 0){
						map.put("id", detail.getMaterialId());
						map.put("warehouseId", warehouseId);
						map.put("customerId", customerId);
						//InventoryReduction ir = new InventoryReduction();
						Long materielId = detail.getMaterialId();
						Integer materielQuantity = detail.getActualQuantity();
						//如果是良品库
						if(source == 1){
							//根据物料ID減良品库存数量
							//ir.inventoryReduction(detail.getMaterialId(), detail.getActualQuantity());
							//根据物料ID查良品库的库存
							//List<ZcInventoryInfoEntity> infoList = cancellingStockDetailService.getInventoryByMid(materielId);
							//遍历减库存（1个物料ID多条库存记录，减后为0的，删除该记录）
							_____________________小连修改前start_________________________
							for(ZcInventoryInfoEntity info : infoList){
								materielQuantity = materielQuantity - info.getmNum();
								//如果物料数量大于库存
								if(materielQuantity > 0){
									//删除这条数据
									cancellingStockDetailService.deleteInventoryById(info.getId());
								}else{
									//修改库存数量
									map.put("id", info.getId());
									map.put("fieldName", "mNum");
									map.put("fieldValue", Math.abs(materielQuantity));
									cancellingStockDetailService.updateInventory(map);
									break;
								}
							}
							________________________end______________________________
							inventoryReduction(materielId, materielQuantity);
						}else{
							//根据物料ID減不良品库存数量
							//ir.rejectsStockReduction(detail.getMaterialId(), detail.getActualQuantity());
							List<ZcRejectsWarehouseEntity> rejestsList = cancellingStockDetailService.queryRejectsByMaterielId(materielId);
							for(ZcRejectsWarehouseEntity rejects : rejestsList){
								materielQuantity = materielQuantity - rejects.getTotality();
								//如果物料数量大于库存
								if(materielQuantity > 0){
									//删除这条数据
									cancellingStockDetailService.deleteRejectsWarehouse(rejects.getId());
								}else{
									//修改库存数量
									map.put("id", rejects.getId());
									map.put("fieldName", "totality");
									map.put("fieldValue", Math.abs(materielQuantity));
									cancellingStockDetailService.updateRejectsWarehouse(map);
									break;
								}
							}
						}
						//修改退库单详情的状态
						map.put("id", detail.getId());
						map.put("fieldName", "status");
						map.put("fieldValue", 1);
						int iu = cancellingStockDetailService.updateCancellingStockDetail3(detail.getId());
					}
				}
			}
			status = "1";
			data = "已退库";
			//查询详情是否都退库
			List<LlmCancellingStocksDetail> detailList = cancellingStockDetailService.getCancellingStockDetailByNumber(list.get(0).getCancellingNumber());
			int sum = 0;
			for(LlmCancellingStocksDetail det : detailList){
				if(det.getStatus() == 1){
					sum += 1;
				}
			}
			//如果详情都退库，修改退库单的状态为已退库
			if(sum == detailList.size()){
				map.put("cancellingNumber", detailList.get(0).getCancellingNumber());
				map.put("fieldName", "status");
				map.put("fieldValue", 1);
				cancellingStockService.updateConcellingStock2(map);
			}
		}
		JSONObject jsonObject= new JSONObject();
		jsonObject.put("status", status);
		jsonObject.put("data", data);
		try {
			ResponseUtil.write(response, jsonObject);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}*/
	
	/**
	 * 减物料良品库的库存
	 * @param materielId 物料ID
	 * @param materielQuantity	物料数量
	 */
	public void inventoryReduction(Long materielId, Integer materielQuantity) {
		//根据物料ID查良品库的库存
		List<ZcInventoryInfoEntity> list = cancellingStockDetailService.getInventoryByMid(materielId);
		//遍历减库存（1个物料ID多条库存记录，减后为0的，删除该记录）
		/*for(ZcInventoryInfoEntity info : list){*/
		for(int i = 0; i < list.size(); i++) {
			//System.out.println("补发数量="+materielQuantity+":  库存数量="+info.getmNum());
			materielQuantity = materielQuantity - list.get(i).getSmallNum();
			//如果物料数量大于库存
			if(materielQuantity > 0){
				//删除这条数据
				//cancellingStockDetailService.deleteInventoryById(info.getId());
				int materielQuantity1;
				materielQuantity1= list.get(i).getBigNum() - materielQuantity ;
				if(materielQuantity1 > 0) {
					//修改库存数量
					Map<String, Object> map = new HashMap<>();
					map.put("id", list.get(i).getId());
					map.put("fieldName", "mNum");
					map.put("fieldValue", Math.abs(materielQuantity1));
					cancellingStockDetailService.updateInventory(map);
					Map<String, Object> map1 = new HashMap<>();
					map1.put("id", list.get(i).getId());
					map1.put("fieldName", "bigNum");
					map1.put("fieldValue", Math.abs(materielQuantity1));
					cancellingStockDetailService.updateInventory(map1);
					Map<String, Object> map2 = new HashMap<>();
					map2.put("id", list.get(i).getId());
					map2.put("fieldName", "smallNum");
					map2.put("fieldValue", 0);
					cancellingStockDetailService.updateInventory(map2);
					break;
				} else {
					//删除这条数据
					cancellingStockDetailService.deleteInventoryById(list.get(i).getId());
					//求绝对值
					inventoryReduction(list.get(i).getMid(), Math.abs(materielQuantity1));
				}
			} else {
				//修改库存数量
				Map<String, Object> map = new HashMap<>();
				map.put("id", list.get(i).getId());
				map.put("fieldName", "smallNum");
				map.put("fieldValue", Math.abs(materielQuantity));
				cancellingStockDetailService.updateInventory(map);
				Map<String, Object> map1 = new HashMap<>();
				map1.put("id", list.get(i).getId());
				map1.put("fieldName", "mNum");
				map1.put("fieldValue", Math.abs(materielQuantity)+list.get(i).getBigNum());
				cancellingStockDetailService.updateInventory(map1);
			}
			return;
		}
	}
	
	/**
	 * 根据供应商和SAP查询所有物料
	 * @param response
	 */
	@RequestMapping("/appGetMaterielByCustomerAndSAP")
	public void appGetMaterielByCustomerAndSAP(String sap, String customerId, HttpServletResponse response){
		ReceiveDetail queryById = receiveDetailService.queryById(Long.parseLong(customerId));
		Receive receive = cancellingStockService.getReceiveByNumber(queryById.getReceiveNumber());
		Map<String, Object> map = new HashMap<>();
		map.put("sap", sap);
		map.put("customerId", Long.parseLong(receive.getSendCompany()));
		List<Materiel> list = cancellingStockService.appGetMaterielByCustomerAndSAP(map);
		List<ReceiveDetail> reList = new ArrayList<ReceiveDetail>();
		for(Materiel m : list){
			ReceiveDetail rd = new ReceiveDetail();
			rd.setId(queryById.getId());
			rd.setMid(m.getId());
			rd.setPici(queryById.getPici());
			rd.setMateriel_name(m.getMateriel_name());
			rd.setMateriel_num(m.getMateriel_num());
			rd.setPacking_quantity(m.getPacking_quantity());
			reList.add(rd);
		}
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("status", "1");
		jsonObject.put("data", reList);
		try {
			ResponseUtil.write(response, jsonObject);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 根据物料SAP查询位置信息
	 * @param number
	 * @param response
	 */
	@RequestMapping("/appGetLocationByNumber")
	public void appGetLocationByNumber(String number, HttpServletResponse response){
		//1、根据物料SAP查询物料的所有条码
		List<CodeMark> codeList = cancellingStockService.getCodeByMaterielNum(number);
		JSONObject jsonObject = new JSONObject();
		if(codeList.size() > 0){
			List<BarCode> list = new ArrayList<>();
			//2、遍历条码查询每个条码的位置
			for(CodeMark code : codeList){
				BarCode bar = cancellingStockService.getLocationByCode(code);
				CodeMark code2 = cancellingStockDetailService.queryCodeByCode(code.getCode());
				if (code2 != null) {
					if(bar != null){
						bar.setMaterielQuantity(code2.getNum());
						ReceiveDetailQuality byCode = inventoryService.queryReceiveByCode(code.getCode());
						code.setReceiveDetailQuality(byCode);
						Materiel materiel = materielService.queryMaterielById(byCode.getMid());
						if (materiel != null) {
							bar.setRemarks(materiel.getMateriel_name());
							bar.setRemark01(materiel.getMateriel_num());
						}
						list.add(bar);
					}
				}
			}
			Set<String> set = new HashSet<>();
			//3、对库位去重
			for(BarCode bc : list){
				set.add(bc.getRemark02());
			}
			List<ZcMaterielInfoEntity> reList = new ArrayList<>();
			//4、对库位数量合并
			for(String str : set){
				ZcMaterielInfoEntity info = new ZcMaterielInfoEntity();
				info.setLocation_code(str);
				for (CodeMark codeMark : codeList) {
					String lname=cancellingStockService.queryCode(codeMark.getCode());
					if(lname.equals(str)) {
						info.setCodeMark(codeList);
					}
				}
				
				List<CodeMark> lists=new ArrayList<>();
				for(CodeMark code : codeList){
					BarCode bar = cancellingStockService.getLocationByCode(code);
					if(bar.getRemark02().equals(str)){
						lists.add(code);
					}
				}
				
				info.setCodeMark(lists);
				for(BarCode bar : list){
					if(str.equals(bar.getRemark02())){
						info.setmNum(info.getmNum() + bar.getMaterielQuantity());
					}
				}
				reList.add(info);
			}
			jsonObject.put("status", "1");
			jsonObject.put("data", reList);
		}else{
			jsonObject.put("status", "0");
			jsonObject.put("message", "无数据");
		}
		try {
			ResponseUtil.write(response, jsonObject);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
